<template>
  <view class="appointments-page">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="nav-back" @tap="goBack">
        <text class="iconfont back-icon">&#xe697;</text>
      </view>
      <text class="page-title">养老院预约记录</text>
      <view class="nav-placeholder" style="width: 40px;"></view>
    </view>
    
    <!-- 内容区域 -->
    <view class="content">
      <!-- 状态筛选 -->
      <view class="filter-tabs">
        <view 
          v-for="(tab, index) in statusTabs" 
          :key="index" 
          class="tab-item" 
          :class="{ active: currentStatus === tab.value }"
          @tap="changeStatus(tab.value)"
        >
          <text class="tab-text">{{tab.label}}</text>
        </view>
      </view>
      
      <!-- 预约列表 -->
      <scroll-view 
        scroll-y 
        class="appointments-list"
        @scrolltolower="loadMore"
      >
        <!-- 空状态 -->
        <view class="empty-state" v-if="filteredAppointments.length === 0">
          <image class="empty-icon" src="../../static/empty.png" mode="aspectFit"></image>
          <text class="empty-text">暂无预约记录</text>
        </view>
        
        <!-- 添加滑动提示 -->
        <view class="swipe-tip" v-if="filteredAppointments.length > 0 && !hasShownTip">
          <view class="swipe-tip-icon">←</view>
          <text class="swipe-tip-text">左滑可查看操作选项</text>
          <text class="swipe-tip-close" @tap="closeTip">知道了</text>
        </view>
        
        <!-- 预约卡片 -->
        <view 
          v-for="(item, index) in filteredAppointments" 
          :key="index" 
          class="appointment-card"
          @touchstart="touchStart($event, index)"
          @touchmove="touchMove($event, index)"
          @touchend="touchEnd($event, index)"
        >
          <!-- 滑动显示的操作按钮 -->
          <view class="swipe-actions">
            <view 
              class="action-btn view-btn" 
              @tap.stop="viewDetail(item)"
            >查看</view>
            <view 
              class="action-btn delete-btn" 
              @tap.stop="deleteAppointment(item)"
            >删除</view>
          </view>
          
          <!-- 卡片内容区 -->
          <view class="card-content" @tap="resetCard(index)">
            <!-- 顶部状态栏 -->
            <view class="card-header">
              <view class="card-status" :class="getStatusClass(item.status)">
                <text class="status-text">{{getStatusText(item.status)}}</text>
              </view>
              <text class="card-time">{{item.createdTime}}</text>
            </view>
            
            <!-- 养老院信息 -->
            <view class="nursing-home-info">
              <view class="home-image-container">
                <image class="home-image" :src="item.image || '../../static/nursing_home.jpg'" mode="aspectFill"></image>
              </view>
              <view class="home-detail">
                <text class="home-name">{{item.name}}</text>
                <view class="home-tags">
                  <text v-for="(tag, tagIndex) in item.tags" :key="tagIndex" class="tag">{{tag}}</text>
                </view>
                <text class="home-address">{{item.address}}</text>
              </view>
            </view>
            
            <!-- 预约信息 -->
            <view class="appointment-info">
              <view class="info-row">
                <view class="info-item">
                  <text class="item-label">联系人</text>
                  <text class="item-value">{{item.contact}}</text>
                </view>
                <view class="info-item">
                  <text class="item-label">联系电话</text>
                  <text class="item-value">{{item.phone}}</text>
                </view>
              </view>
              <view class="info-item remark-item" v-if="item.remark">
                <text class="item-label">备注</text>
                <text class="item-value remark-value">{{item.remark}}</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 加载状态 -->
        <view class="loading-state" v-if="loading && filteredAppointments.length > 0">
          <text class="loading-text">加载中...</text>
        </view>
        
        <!-- 无更多数据 -->
        <view class="no-more" v-if="!hasMore && filteredAppointments.length > 0">
          <text class="no-more-text">— 没有更多数据了 —</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';

// 状态Tab
const statusTabs = [
  { label: '全部', value: 'all' },
  { label: '待确认', value: 'pending' },
  { label: '已确认', value: 'confirmed' },
  { label: '已完成', value: 'completed' },
  { label: '已取消', value: 'cancelled' }
];

// 提示相关
const hasShownTip = ref(false);

// 关闭提示
const closeTip = () => {
  hasShownTip.value = true;
  // 可以存储到本地，下次不再显示
  uni.setStorageSync('swipeTipShown', 'true');
};

// 当前选中状态
const currentStatus = ref('all');

// 模拟数据
const appointments = ref([]);

// 加载状态
const loading = ref(false);
const hasMore = ref(true);

// 获取筛选后的预约记录
const filteredAppointments = computed(() => {
  if (currentStatus.value === 'all') {
    return appointments.value;
  }
  return appointments.value.filter(item => item.status === currentStatus.value);
});

// 页面加载时执行
onMounted(() => {
  loadAppointments();
  // 检查是否已经显示过提示
  try {
    const tipShown = uni.getStorageSync('swipeTipShown');
    if (tipShown === 'true') {
      hasShownTip.value = true;
    }
  } catch (e) {
    // 忽略错误
  }
  // 禁用页面级下拉刷新
  setTimeout(() => {
    const pages = getCurrentPages();
    const page = pages[pages.length - 1];
    if (page && page.$getAppWebview) {
      const webview = page.$getAppWebview();
      if (webview && webview.setStyle) {
        webview.setStyle({
          pullToRefresh: {
            support: false
          }
        });
      }
    }
  }, 100);
});

// 加载预约数据
const loadAppointments = () => {
  loading.value = true;
  
  // 模拟异步加载数据
  setTimeout(() => {
    // 模拟数据
    const mockData = [
      {
        id: '1001',
        name: '康乐养老院',
        image: '../../static/nursing_home.jpg',
        tags: ['公办非营利性', '医养结合'],
        address: '北京市海淀区西北旺东路10号院',
        status: 'pending',
        createdTime: '2023-09-10 14:30',
        appointmentTime: '2023-09-15 10:00',
        service: '参观考察',
        contact: '张先生',
        phone: '138****1234',
        remark: '希望了解入住条件和费用标准',
        swiped: false
      },
      {
        id: '1002',
        name: '福寿康养中心',
        image: '../../static/nursing_home.jpg',
        tags: ['民办非营利性', '文化养老'],
        address: '北京市朝阳区望京花园东区5号楼',
        status: 'confirmed',
        createdTime: '2023-08-25 09:15',
        appointmentTime: '2023-08-30 14:30',
        service: '健康评估',
        contact: '李女士',
        phone: '139****5678',
        remark: '',
        swiped: false
      },
      {
        id: '1003',
        name: '颐和老年公寓',
        image: '../../static/nursing_home.jpg',
        tags: ['民办营利性', '高端养老'],
        address: '北京市丰台区南四环西路128号院',
        status: 'completed',
        createdTime: '2023-07-15 11:30',
        appointmentTime: '2023-07-20 11:00',
        service: '入住咨询',
        contact: '王先生',
        phone: '137****9012',
        remark: '关注医疗服务和护理配置',
        swiped: false
      },
      {
        id: '1004',
        name: '怡年养老中心',
        image: '../../static/nursing_home.jpg',
        tags: ['公办营利性', '医养结合'],
        address: '北京市西城区德胜门外大街13号',
        status: 'cancelled',
        createdTime: '2023-06-05 16:45',
        appointmentTime: '2023-06-10 15:30',
        service: '参观考察',
        contact: '赵女士',
        phone: '136****3456',
        remark: '希望了解护理团队的资质和服务内容',
        swiped: false
      }
    ];
    
    appointments.value = [...appointments.value, ...mockData];
    loading.value = false;
    
    // 模拟没有更多数据
    if (appointments.value.length >= 8) {
      hasMore.value = false;
    }
  }, 1500);
};

// 切换状态筛选
const changeStatus = (status) => {
  currentStatus.value = status;
};

// 下拉刷新
const onRefresh = () => {
  // 清空现有数据
  appointments.value = [];
  hasMore.value = true;
  // 重新加载数据
  loadAppointments();
};

// 上拉加载更多
const loadMore = () => {
  if (loading.value || !hasMore.value) return;
  loadAppointments();
};

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    pending: 'status-pending',
    confirmed: 'status-confirmed',
    completed: 'status-completed',
    cancelled: 'status-cancelled'
  };
  return statusMap[status] || '';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待确认',
    confirmed: '已确认',
    completed: '已完成',
    cancelled: '已取消'
  };
  return statusMap[status] || '未知状态';
};

// 查看详情
const viewDetail = (item) => {
  // 跳转到养老院详情页
  uni.navigateTo({
    url: `/pages/nursing-home-detail/index?id=${item.id}`
  });
};

// 取消预约
const cancelAppointment = (item) => {
  uni.showModal({
    title: '提示',
    content: '确定要取消此预约吗？',
    success: (res) => {
      if (res.confirm) {
        // 模拟取消操作
        const index = appointments.value.findIndex(appointment => appointment.id === item.id);
        if (index !== -1) {
          appointments.value[index].status = 'cancelled';
          
          uni.showToast({
            title: '预约已取消',
            icon: 'success'
          });
        }
      }
    }
  });
};

// 添加评价
const addComment = (item) => {
  uni.navigateTo({
    url: `/pages/nursing-home-detail/comments?id=${item.id}&action=add`
  });
};

// 设置提醒
const setReminder = (item) => {
  uni.showToast({
    title: '提醒已设置',
    icon: 'success'
  });
};

// 删除预约记录
const deleteAppointment = (item) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除此预约记录吗？删除后将无法恢复。',
    success: (res) => {
      if (res.confirm) {
        // 模拟删除操作
        const index = appointments.value.findIndex(appointment => appointment.id === item.id);
        if (index !== -1) {
          appointments.value.splice(index, 1);
          
          uni.showToast({
            title: '已删除',
            icon: 'success'
          });
        }
      }
    }
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 触摸相关变量和函数
const touchStartX = ref(0);
const touchSwipeThreshold = 80; // 滑动阈值

// 触摸开始
const touchStart = (event, index) => {
  touchStartX.value = event.touches[0].clientX;
  // 重置其他卡片
  appointments.value.forEach((item, idx) => {
    if (idx !== index && item.swiped) {
      item.swiped = false;
      const otherCard = document.querySelectorAll('.appointment-card')[idx];
      if (otherCard) {
        const otherContent = otherCard.querySelector('.card-content');
        if (otherContent) {
          otherContent.style.transform = 'translateX(0)';
        }
      }
    }
  });
};

// 触摸移动
const touchMove = (event, index) => {
  const currentX = event.touches[0].clientX;
  const diff = currentX - touchStartX.value;
  const card = event.currentTarget;
  
  if (!card) return;
  
  const content = card.querySelector('.card-content');
  if (!content) return;
  
  // 只允许向左滑动显示按钮
  if (diff < 0) {
    const offset = Math.max(diff, -140); // 限制最大滑动距离
    content.style.transform = `translateX(${offset}px)`;
  } else if (appointments.value[index].swiped) {
    // 如果已经滑开，允许右滑恢复
    const offset = Math.min(diff, 0);
    content.style.transform = `translateX(${-140 + offset}px)`;
  }
};

// 触摸结束
const touchEnd = (event, index) => {
  const card = event.currentTarget;
  if (!card) return;
  
  const content = card.querySelector('.card-content');
  if (!content) return;
  
  const currentTransform = content.style.transform || '';
  const match = currentTransform.match(/translateX\(([-\d.]+)px\)/);
  const currentX = match ? parseFloat(match[1]) : 0;
  
  // 根据滑动距离决定是否显示操作按钮
  if (currentX < -touchSwipeThreshold) {
    content.style.transform = 'translateX(-140px)';
    appointments.value[index].swiped = true;
  } else {
    content.style.transform = 'translateX(0)';
    appointments.value[index].swiped = false;
  }
};

// 点击卡片内容区域时重置卡片
const resetCard = (index) => {
  if (appointments.value[index].swiped) {
    appointments.value[index].swiped = false;
    const card = document.querySelectorAll('.appointment-card')[index];
    if (card) {
      const content = card.querySelector('.card-content');
      if (content) {
        content.style.transform = 'translateX(0)';
      }
    }
  }
};
</script>

<style lang="scss">
page {
  background-color: #f5f5f5;
  min-height: 100%;
}

.appointments-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  
  .header {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 44px;
    background-color: #fff;
    border-bottom: 1px solid rgba(195, 227, 227, 0.2);
    
    .nav-back {
      width: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .back-icon {
        font-size: 20px;
        color: #5d4037;
      }
    }
    
    .page-title {
      flex: 1;
      text-align: center;
      font-size: 18px;
      font-weight: 500;
      color: #5d4037;
    }
  }
  
  .content {
    flex: 1;
    display: flex;
    flex-direction: column;
    
    .filter-tabs {
      display: flex;
      background-color: #fff;
      padding: 0 5px;
      height: 44px;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
      
      .tab-item {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        
        .tab-text {
          font-size: 14px;
          color: #666;
        }
        
        &.active {
          .tab-text {
            color: #2c7873;
            font-weight: 500;
          }
          
          &:after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 30%;
            width: 40%;
            height: 3px;
            background-color: #2c7873;
            border-radius: 3px;
          }
        }
      }
    }
    
    .appointments-list {
      flex: 1;
      padding: 15px 10px;
      
      .empty-state {
        margin-top: 100px;
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .empty-icon {
          width: 120px;
          height: 120px;
          margin-bottom: 20px;
        }
        
        .empty-text {
          color: #999;
          font-size: 15px;
        }
      }
      
      .appointment-card {
        position: relative;
        background-color: #fff;
        border-radius: 16px;
        margin-bottom: 20px;
        overflow: hidden;
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
        width: 90%;
        margin-left: auto;
        margin-right: auto;
        
        &:active .card-content {
          background-color: #f9f9f9; /* 按下时的轻微反馈 */
        }
        
        .card-content {
          width: 100%;
          position: relative;
          z-index: 1;
          transition: transform 0.3s cubic-bezier(0.25, 0.8, 0.25, 1) !important;
          background-color: #fff;
          will-change: transform; /* 优化动画性能 */
        }
        
        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 16px;
          border-bottom: 1px solid #f5f5f5;
          
          .card-status {
            padding: 4px 10px;
            border-radius: 20px;
            
            .status-text {
              font-size: 12px;
              font-weight: 500;
            }
            
            &.status-pending {
              background-color: #fff8e1;
              
              .status-text {
                color: #ffa000;
              }
            }
            
            &.status-confirmed {
              background-color: #e3f2fd;
              
              .status-text {
                color: #1976d2;
              }
            }
            
            &.status-completed {
              background-color: #e8f5e9;
              
              .status-text {
                color: #43a047;
              }
            }
            
            &.status-cancelled {
              background-color: #f5f5f5;
              
              .status-text {
                color: #9e9e9e;
              }
            }
          }
          
          .card-time {
            font-size: 12px;
            color: #9e9e9e;
          }
        }
        
        .nursing-home-info {
          display: flex;
          padding: 16px;
          border-bottom: 1px solid #f5f5f5;
          
          .home-image-container {
            width: 80px;
            height: 80px;
            border-radius: 10px;
            overflow: hidden;
            margin-right: 14px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            
            .home-image {
              width: 100%;
              height: 100%;
            }
          }
          
          .home-detail {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            
            .home-name {
              font-size: 17px;
              font-weight: 600;
              color: #333;
              margin-bottom: 8px;
            }
            
            .home-tags {
              display: flex;
              flex-wrap: wrap;
              margin-bottom: 8px;
              
              .tag {
                font-size: 11px;
                color: #6FB3B8;
                background-color: rgba(111, 179, 184, 0.12);
                padding: 3px 8px;
                border-radius: 12px;
                margin-right: 6px;
                margin-bottom: 6px;
              }
            }
            
            .home-address {
              font-size: 13px;
              color: #757575;
              line-height: 1.4;
            }
          }
        }
        
        .appointment-info {
          padding: 16px;
          
          .info-row {
            display: flex;
            margin-bottom: 12px;
            
            .info-item {
              flex: 1;
              margin-right: 10px;
              
              &:last-child {
                margin-right: 0;
              }
            }
          }
          
          .info-item {
            display: flex;
            flex-direction: column;
            margin-bottom: 8px;
            
            &.remark-item {
              margin-top: 4px;
            }
            
            .item-label {
              font-size: 12px;
              color: #9e9e9e;
              margin-bottom: 4px;
            }
            
            .item-value {
              font-size: 14px;
              color: #424242;
              word-wrap: break-word;
              
              &.remark-value {
                font-size: 13px;
                color: #757575;
                line-height: 1.4;
              }
            }
          }
        }
        
        .swipe-actions {
          position: absolute;
          top: 0;
          right: 0;
          height: 100%;
          display: flex;
          align-items: center;
          z-index: 0;
          width: 140px; /* 确保宽度与滑动距离一致 */
          
          .action-btn {
            height: 100%;
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 15px;
            font-weight: 500;
            
            &::before {
              content: '';
              width: 24px;
              height: 24px;
              margin-bottom: 4px;
              background-position: center;
              background-repeat: no-repeat;
              background-size: contain;
            }
          }
          
          .view-btn {
            background-color: #2c7873;
            
            &::before {
              content: '\e64f'; /* 使用图标 */
              font-family: "iconfont";
              font-size: 20px;
            }
          }
          
          .delete-btn {
            background-color: #f44336;
            
            &::before {
              content: '\e6b4'; /* 使用图标 */
              font-family: "iconfont";
              font-size: 20px;
            }
          }
        }
      }
      
      .loading-state {
        text-align: center;
        padding: 15px 0;
        
        .loading-text {
          font-size: 14px;
          color: #999;
        }
      }
      
      .no-more {
        text-align: center;
        padding: 15px 0;
        
        .no-more-text {
          font-size: 12px;
          color: #ccc;
        }
      }
    }
  }
}

// 滑动提示样式
.swipe-tip {
  position: fixed;
  bottom: 30px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(44, 120, 115, 0.9);
  color: #fff;
  padding: 10px 18px;
  border-radius: 24px;
  z-index: 999;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  animation: pulse 1.5s infinite alternate;
  
  @keyframes pulse {
    0% { transform: translateX(-50%) scale(1); }
    100% { transform: translateX(-50%) scale(1.05); }
  }
  
  .swipe-tip-icon {
    font-size: 18px;
    margin-right: 6px;
    font-weight: bold;
    animation: slideLeft 1s infinite;
    
    @keyframes slideLeft {
      0% { transform: translateX(0); }
      50% { transform: translateX(-4px); }
      100% { transform: translateX(0); }
    }
  }
  
  .swipe-tip-text {
    font-size: 14px;
    margin-right: 12px;
  }
  
  .swipe-tip-close {
    font-size: 14px;
    color: #fff;
    background-color: rgba(255, 255, 255, 0.2);
    padding: 3px 8px;
    border-radius: 12px;
  }
}

// 添加图标字体样式（确保已加载iconfont）
@font-face {
  font-family: 'iconfont';
  /* 字体路径 */
  src: url('../../static/iconfont.ttf');
}
</style> 